package com.china08.yxyapi.api.manage.stu.mystudy.homework.workreport;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues.Article;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReportQues;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.es.ElasticYxyYxyQuesResourceRespository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.util.DateUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

/**
 * 家长端作业系统 查看作业
 * 
 * @author yangyunying
 *
 */

/*
 * 重构 2018年1月11日09:48:11 李亚松
 * 1.从任务题表中查出来所有题，并且将题按照顺序封装为两种：1.题库内的题：homeworkTaskReportQuesModelLst
 * 2.平台提供的阅读类和通知类 封装到两个map中
 * 2.从查出学生答案，按照题ID赋值给对应的题*******这样做是为了兼容以前的学生没有答题记录显示不出来试题详情的问题。
 */
@CrossOrigin
@RestController
public class WorkReportCheckHomeFind1Controller {

    @Autowired
    private HomeworkTaskReportQuesRepository homeworkTaskReportQuesRepository;

    @Autowired
    private HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    private ElasticYxyYxyQuesResourceRespository elasticYxyYxyQuesResourceRespository;

    @Autowired
    private HomeworkTaskQuesRepository homeworkTaskQuesRepository;

    /**
     * 查看家庭作业
     * 
     * @param request
     * @param response
     * @param req
     * @param respModel
     * @return
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    // @ApiOperation(value = "查看作业")
    @ResponseBody
    @RequestMapping(value = "/api_yw/manage/stu/mystudy/workreport/checkhome1/srh", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(@RequestBody ReqModel req, RespModel respModel)
            throws JsonParseException, JsonMappingException, IOException {
        long startQuery = System.currentTimeMillis();
        respModel = new RespModel();

        String studentId = req.studentId;
        String taskId = req.taskId;
        Assert.isTrue(!StringUtils.isBlank(studentId), "学生ID不能为空");
        Assert.isTrue(!StringUtils.isBlank(taskId), "作业ID不能为空");

        // 查询作业标题 班级名 作业用时 正确率 评语
        HomeworkTaskReport homeworkTaskReport = homeworkTaskReportRepository.findByStudentIdAndTaskId(studentId,
                taskId);
        // 基础数据
        respModel.title = homeworkTaskReport.getTitle();
        respModel.taskType = homeworkTaskReport.getTaskType();
        respModel.studentNick = homeworkTaskReport.getStudentNick();
        respModel.className = homeworkTaskReport.getClassName();
        respModel.duration = DateUtils.getDurationDateByDurationCount(homeworkTaskReport.getDuration() * 1000);
        respModel.statusOfFinished = homeworkTaskReport.getStatusOfFinished();
        // 将double类型的数据保存到小数点的后两位
        DecimalFormat df = new DecimalFormat("######0.0");
        respModel.scoreRate = Double.parseDouble(df.format(homeworkTaskReport.getScoreRate()));
        respModel.evaluate = homeworkTaskReport.getEvaluate();
        System.out.println("查询基础数据用时 正确率 评语 : " + (System.currentTimeMillis() - startQuery));
        // #######组装试题 #########

        // 查询所有题信息 （来源于试题）
        List<HomeworkTaskQues> homeworkTaskQuess = homeworkTaskQuesRepository.findByTaskIdOrderByOrder(taskId);
        // 查询所有学生答题题信息 （来源于答题记录）
        List<HomeworkTaskReportQues> homeworkTaskReportQuesLst = homeworkTaskReportQuesRepository
                .findByStudentIdAndTaskIdOrderByOrder(studentId, taskId);
        // 封装答题记录
        Map<String, HomeworkTaskReportQues> homeworkTaskReportQuesMap = new HashMap<String, HomeworkTaskReportQues>();
        for (HomeworkTaskReportQues homeworkTaskReportQues : homeworkTaskReportQuesLst) {
            homeworkTaskReportQuesMap.put(homeworkTaskReportQues.getQuesId(), homeworkTaskReportQues);
        }
        if (homeworkTaskQuess == null || homeworkTaskQuess.size() == 0) {
            respModel.pageIsShow = false;
        }
        // 题库题列表
        List<HomeworkTaskReportQuesModel> homeworkTaskReportQuesModelLst = new ArrayList<>();
        // 教师出题和平台题列表
        List<HomeworkTaskReportQuesModel> noticeHomeworkTaskReportQuesModelLst = new ArrayList<>();
        // 单选试题值
        Integer singleCount = 0;
        // 多选试题值
        Integer moreCount = 0;
        // 填空题
        Integer fillBlanksCount = 0;
        // 简答题
        Integer simpleCount = 0;
        // 通知试题值
        Integer noticeCount = 0;
        // 阅读试题值
        Integer yueduCount = 0;

        // 遍历每道题，装饰答题记录
        for (HomeworkTaskQues homeworkTaskQues : homeworkTaskQuess) {
            HomeworkTaskReportQues homeworkTaskReportQues = homeworkTaskReportQuesMap.get(homeworkTaskQues.getQuesId());
            if (homeworkTaskReportQues == null) { // 没有答题记录创建答题记录
                homeworkTaskReportQues = getHomeworkTaskReportQuesOfHomeworkTaskQues(studentId, taskId,
                        homeworkTaskQues);
            }
            // 题库题封装
            if ("0".equals(homeworkTaskQues.getQuesType())) {
                singleCount += 1;
                addQuesToHomeworkTaskReportQuesModelLst(startQuery, homeworkTaskReportQuesModelLst,
                        homeworkTaskReportQues);
            }
            if ("1".equals(homeworkTaskQues.getQuesType())) {
                moreCount += 1;
                addQuesToHomeworkTaskReportQuesModelLst(startQuery, homeworkTaskReportQuesModelLst,
                        homeworkTaskReportQues);
            }
            if ("3".equals(homeworkTaskQues.getQuesType())) {
                fillBlanksCount += 1;
                addQuesToHomeworkTaskReportQuesModelLst(startQuery, homeworkTaskReportQuesModelLst,
                        homeworkTaskReportQues);
            }
            if ("4".equals(homeworkTaskQues.getQuesType())) {
                simpleCount += 1;
                addQuesToHomeworkTaskReportQuesModelLst(startQuery, homeworkTaskReportQuesModelLst,
                        homeworkTaskReportQues);
            }
            // 通知阅读类题封装
            if ("2".equals(homeworkTaskQues.getQuesType())) {
                noticeCount += 1;
                respModel.ifNeedSumbit = homeworkTaskQues.getIfNeedSumbit();
                addQuesToNoticeHomeworkTaskReportQuesModelLst(noticeHomeworkTaskReportQuesModelLst, homeworkTaskQues,
                        homeworkTaskReportQues);
            }
            if ("5".equals(homeworkTaskQues.getQuesType())) {
                yueduCount += 1;
                addQuesToNoticeHomeworkTaskReportQuesModelLst(noticeHomeworkTaskReportQuesModelLst, homeworkTaskQues,
                        homeworkTaskReportQues);
            }
        }
        // 试题+ 填空 + 简答
        respModel.homeworkTaskReportQuesLst = homeworkTaskReportQuesModelLst;
        // 阅读和通知类
        respModel.noticeHomeworkTaskReportQuesLst = noticeHomeworkTaskReportQuesModelLst;
        // 查询单选题和多选题和通知题的数量
        respModel.singleCount = singleCount;
        respModel.moreCount = moreCount;
        respModel.fillBlanksCount = fillBlanksCount;
        respModel.simpleCount = simpleCount;
        respModel.noticeCount = noticeCount;
        respModel.yueDuCount = yueduCount;
        System.out.println("接口结束  耗时 : " + (System.currentTimeMillis() - startQuery));
        return respModel;
    }

    private void addQuesToNoticeHomeworkTaskReportQuesModelLst(
            List<HomeworkTaskReportQuesModel> noticeHomeworkTaskReportQuesModelLst, HomeworkTaskQues homeworkTaskQues,
            HomeworkTaskReportQues homeworkTaskReportQues) {
        HomeworkTaskReportQuesModel noticeHomeworkTaskReportQuesModel = new HomeworkTaskReportQuesModel();
        noticeHomeworkTaskReportQuesModel.quesContent = homeworkTaskQues.getQuesContent();// 老师布置作业编辑的内容
        noticeHomeworkTaskReportQuesModel.questionType = homeworkTaskQues.getQuesType();
        noticeHomeworkTaskReportQuesModel.order = homeworkTaskQues.getOrder();
        noticeHomeworkTaskReportQuesModel.quesId = homeworkTaskQues.getQuesId();
        noticeHomeworkTaskReportQuesModel.title = homeworkTaskQues.getTitle();
        noticeHomeworkTaskReportQuesModel.answerOfMy = homeworkTaskReportQues.getAnswerOfMy();
        noticeHomeworkTaskReportQuesModel.answerText = homeworkTaskReportQues.getAnswerText();
        noticeHomeworkTaskReportQuesModel.answerOfMyImgs = homeworkTaskReportQues.getAnswerImgs();
        noticeHomeworkTaskReportQuesModel.mark = homeworkTaskReportQues.getMark();
        noticeHomeworkTaskReportQuesModel.passed = homeworkTaskReportQues.getPassed();
        noticeHomeworkTaskReportQuesModel.mark = homeworkTaskReportQues.getMark();
        noticeHomeworkTaskReportQuesModel.quesArticle = (homeworkTaskReportQues.getQuesArticle() != null
                && homeworkTaskReportQues.getQuesArticle().size() > 0) ? homeworkTaskReportQues.getQuesArticle()
                        : homeworkTaskQues.getQuesArticle();
        if (noticeHomeworkTaskReportQuesModel.quesArticle != null
                && noticeHomeworkTaskReportQuesModel.quesArticle.size() > 0) {
            for (Article article : noticeHomeworkTaskReportQuesModel.quesArticle) {
                if (StringUtils.isBlank(article.getArticle_name())) {
                    article.setArticle_name("未命名文件");
                }
            }
        }
        noticeHomeworkTaskReportQuesModelLst.add(noticeHomeworkTaskReportQuesModel);
    }

    private void addQuesToHomeworkTaskReportQuesModelLst(long startQuery,
            List<HomeworkTaskReportQuesModel> homeworkTaskReportQuesModelLst,
            HomeworkTaskReportQues homeworkTaskReportQues) {
        HomeworkTaskReportQuesModel homeworkTaskReportQuesModel = new HomeworkTaskReportQuesModel();
        homeworkTaskReportQuesModel.questionType = homeworkTaskReportQues.getQuestionType();
        homeworkTaskReportQuesModel.answerText = homeworkTaskReportQues.getAnswerText();
        homeworkTaskReportQuesModel.answerOfMy = homeworkTaskReportQues.getAnswerOfMy();
        homeworkTaskReportQuesModel.answerOfMyImgs = homeworkTaskReportQues.getAnswerImgs();
        homeworkTaskReportQuesModel.answerOfQues = homeworkTaskReportQues.getAnswerOfQues();
        homeworkTaskReportQuesModel.passed = homeworkTaskReportQues.getPassed();
        homeworkTaskReportQuesModel.mark = homeworkTaskReportQues.getMark();
        homeworkTaskReportQuesModel.order = homeworkTaskReportQues.getOrder();
        homeworkTaskReportQuesModel.quesId = homeworkTaskReportQues.getQuesId();
        homeworkTaskReportQuesModel.difficultyLevel = homeworkTaskReportQues.getDifficultyLevel();
        homeworkTaskReportQuesModel.knowNameLst = homeworkTaskReportQues.getKnowNameLst();
        System.out.println("开始查询试题 begin : " + (System.currentTimeMillis() - startQuery));
        ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = null;
        elasticYxyYxyQuesResource = elasticYxyYxyQuesResourceRespository.findById(homeworkTaskReportQues.getQuesId());
        System.out.println("开始查询试题 end : " + (System.currentTimeMillis() - startQuery));
        homeworkTaskReportQuesModel.quesBody = elasticYxyYxyQuesResource;
        System.out.println("解析试题 end : " + (System.currentTimeMillis() - startQuery));
        homeworkTaskReportQuesModelLst.add(homeworkTaskReportQuesModel);
    }

    private HomeworkTaskReportQues getHomeworkTaskReportQuesOfHomeworkTaskQues(String studentId, String taskId,
            HomeworkTaskQues homeworkTaskQues) {
        HomeworkTaskReportQues homeworkTaskReportQues;
        homeworkTaskReportQues = new HomeworkTaskReportQues();
        homeworkTaskReportQues.setQuestionType(homeworkTaskQues.getQuesType());
        homeworkTaskReportQues.setStudentId(studentId);
        homeworkTaskReportQues.setTaskId(taskId);
        homeworkTaskReportQues.setOrder(homeworkTaskQues.getOrder());
        homeworkTaskReportQues.setQuesId(homeworkTaskQues.getQuesId());
        homeworkTaskReportQues.setPassed(0);
        homeworkTaskReportQues.setDifficultyLevel(homeworkTaskQues.getDifficultyLevel());
        homeworkTaskReportQues.setKnowNameLst(homeworkTaskQues.getKnowName());
        homeworkTaskReportQues.setQuesArticle(homeworkTaskQues.getQuesArticle());
        homeworkTaskReportQues.setAnswerText(null);
        homeworkTaskReportQues.setAnswerImgs(null);
        homeworkTaskReportQues.setAnswerOfMy(null);
        return homeworkTaskReportQues;
    }

    protected static class ReqModel extends YxyApiReqModel {
        // 任务id
        public String taskId;
        // 学生id
        public String studentId;
        // 判断是否只看错题
        @Deprecated
        public Integer passed;
    }

    /**
     * 试题每道题详细信息
     */
    public class HomeworkTaskReportQuesModel {
        // 题目的类型
        public String questionType;
        // 通知作业的标题
        public String title;
        // 通知类试题的答案
        public String answerText;
        // 我的回答
        public String answerOfMy;
        // 我的回答 - IMG
        public List<String> answerOfMyImgs;
        // 单选多选正确答案
        public String answerOfQues;
        // 试题类作业是否正确 0-错误 , 1-正确 ,2-半对 20% ,3-半对 30% ,4-半对 80%
        public Integer passed;
        // 通知类作业是否正确 1-优, 2-良, 3-中, 4-差
        @Deprecated
        public Integer notifyPassed;
        // 主观题得分
        public Integer mark = null;
        // 题的序号
        public Integer order;
        // 题的详细信息
        public Object quesBody;
        // 题id
        public String quesId;
        // 通知类作业，上传的图片Url
        public List<String> quesImage;
        // 通知类作业，上传的文档,需要存储文档地址，文档的名称
        public List<Article> quesArticle;
        // 通知类作业 老师布置作业编辑的内容
        public String quesContent;
        // 单选题号模拟
        public Integer count = 0;
        // 多选题号模拟
        public Integer count2 = 0;
        // 填空
        public Integer count3 = 0;
        // 简答
        public Integer count4 = 0;
        // 题的难易程度
        public Integer difficultyLevel;
        // 知识点:Name
        public List<String> knowNameLst;

    }

    protected static class RespModel extends YxyApiRespModel {
        // 没有题的时候，显示作业已删除
        public Boolean pageIsShow = true;
        // 作业完成情况:-1-逾期未提交,0-未做,1-完成 ,2-已批阅,3-答题中
        public Integer statusOfFinished;
        // 作业类型
        public String taskType;
        // 查看作业页面的标题
        public String title;
        // 所在班级的名称
        public String className;
        // 学生名称
        public String studentNick;
        // 作业用时
        public String duration;
        // 得分率
        public Double scoreRate;
        // 教师评语
        public String evaluate;
        // 通知题
        public List<HomeworkTaskReportQuesModel> noticeHomeworkTaskReportQuesLst;
        // 试题
        public List<HomeworkTaskReportQuesModel> homeworkTaskReportQuesLst;
        // 单选题的数量
        public Integer singleCount;
        // 多选题的数量
        public Integer moreCount;
        // 通知试题的数量
        public Integer noticeCount;
        // 阅读试题的数量
        public Integer yueDuCount;
        // 填空题
        public Integer fillBlanksCount;
        // 简答题
        public Integer simpleCount;

        // 判断当前时间是否超过截止时间(0:未超过、1：已超过)
        @Deprecated
        public Integer booTime;
        // 是否能查看答案 0 是不显示 1 是显示
        @Deprecated
        public Integer isShowAnswer;
        // 发布答案解析：0--提交作业后，1--截止时间后
        @Deprecated
        public Integer publishAnswer;
        // 通知类作业是否需要学生在线提交true需要,false不需要
        public Boolean ifNeedSumbit;
        // 正确率
        @Deprecated
        public Double rightRate;
    }
}
